﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Uniforax.Core.Common;
using Uniforax.Core.GameObjects;

namespace Uniforax.Core.GameActions
{
    public class DestoryGameObjectAction : BaseGameAction
    {
        public PosId OldPosId { get; set; }
        public string ObjectId { get; set; }
        public BaseGameObject ClonedGameObject { get; set; }

        public DestoryGameObjectAction(BaseGameObject gameObject)
        {
            OldPosId = gameObject.PosId;
            ObjectId = gameObject.ObjectId;
            ClonedGameObject = gameObject.Clone() as BaseGameObject;
        }

        public override void Execute(ActionContext context)
        {
            var world = context.GameWorld;
            var posId = OldPosId;
            var grid = world.GetGrid(posId);
            var objectId = ObjectId;
            var gameObject = grid.GetPlacedObject(objectId);

            GameObjectLeaveFromGrid(context, grid, gameObject);

            gameObject.OnDestory(context);
        }

        private static void GameObjectLeaveFromGrid(ActionContext context, WorldFramework.Grid grid, BaseGameObject gameObject)
        {
            // 先判定移除，再判定销毁。
            var leaveContext = new GameObjectLeaveGridMovementContext()
            {
                GameObject = gameObject,
                OldGrid = grid
            };

            grid.RemovePlacedObject(gameObject);
            grid.OnGameObjectLeave(context, leaveContext);
            gameObject.OnLeaveGrid(context, leaveContext);
        }

        public override void Undo(ActionContext context)
        {
            var world = context.GameWorld;
            var posId = OldPosId;
            var grid = world.GetGrid(posId);
            var objectId = ObjectId;
            var gameObject = ClonedGameObject.Clone() as BaseGameObject;

            grid.PlaceObject(gameObject);

        }

    }
}
